import {Avatar, Tag, Typography} from "antd";
import {useUserState} from "../states/user.ts";
import {getUserInfo, updateUserInfo, type UserInfo} from "../request/user.ts";

/**
 * the personal center display following:
 * 1. the username
 * 2. updating time on this user
 * 3. email of the user
 * 4. user status in GitHub.io
 */
export function PersonalCenter() {
    const userState = useUserState()

    /**
     * When username has changed and the hook be called
     * if and only if the button of `logout` had clicked then function will be called
     * @param value username value
     */
    const userNameChangeHandler = (value: string) => {
        updateUserInfo({
            ...userState.userInfo,
            username: value
        } as UserInfo).then(() => {
            getUserInfo(value).then(res => {
                userState.setUserInfo(res.data.body)
            })
        })
    }

    return <div>
        <Typography.Title>个人中心</Typography.Title>
        <div className='flex flex-row items-center gap-3'>
            <Avatar size='large' className='scale-125' src={(userState.userInfo as UserInfo).avatar}/>
            <div>
                <Typography.Title
                    editable={{
                        onChange: userNameChangeHandler
                    }}
                    level={4}>{(userState.userInfo as UserInfo).username}</Typography.Title>
                <span
                    className='text-gray-600'>上次更新时间{new Date((userState.userInfo as UserInfo).updatedAt).toLocaleString()}</span>
            </div>
        </div>
        {/*other information*/}
        <div className='flex flex-row gap-0.5'>
            <Typography.Text>
                <Tag color='blue'>{(userState.userInfo as UserInfo).email}</Tag>
            </Typography.Text>
            <Typography.Text>
                <Tag color='success'>{(userState.userInfo as UserInfo).status}</Tag>
            </Typography.Text>
            <Typography.Text>
                <Tag color='red'>{new Date((userState.userInfo as UserInfo).updatedAt).toLocaleString()}</Tag>
            </Typography.Text>
        </div>
        {/*TODO: this place will put a checkbox for non-asynchronize to Github.io*/}
        {/*<Checkbox>是否将此信息同步到你的Github.io</Checkbox>*/}
    </div>
}